<?php

namespace MarketServer\Model;

/**
 * Description of AdminModel
 *
 * @since 1.0 <2015-3-5> SoChishun <14507247@qq.com> Added.
 */
class AdminModel extends AppbaseModel {

    protected $tableName = 'tuser';
// 命名范围
    protected $_scope = array(
        'idtext' => array(
            'field' => array('site_id as id', "concat(user_name,'[',site_id,']') as text"),
            'cache' => true,
        ),
        'export' => array(
            'field' => "site_id as '租户ID', user_name as '用户名'",
            'order' => 'site_id',
            'cache' => true,
        ),
        'item_list' => array(
            'field' => 'id, site_id, user_name, personal_name, telphone, role_id, user_state, login_count, online_state, create_time',
            'order' => 'id desc',
            'cache' => true,
        ),
    );
    protected $_auto = array(
        array('user_state', 1, self::MODEL_INSERT),
    );
    protected $patchValidate = true;

    public function scope_fields($scope = 'idtext') {
        return $this->base_get_scope_fields($scope);
    }

    /**
     * 修改密码
     * @param string|array $where 查询条件
     * @param string $pwd 新密码
     * @return false|int 成功则返回受影响数量,失败返回false
     * @since 1.0 2015-3-6 by sutroon
     */
    public function update_password($where, $pwd) {
        $result = $M->where($where)->setField('password', $pwd);
        $condition = is_array($where) ? print_r($where, true) : $where;
        D('Log')->log_user_operate($result, "[修改密码%] $condition, password=$pwd", 0, '修改密码');
        return $result;
    }
    
    /**
     * 获取n个月未登陆的用户列表
     * @since 1.0 <2015-8-6> SoChishun Added.
     */
    public function get_admin_list_of_months_ago($month=3){
        
    }

    /**
     * 保存管理员
     * @param int $admin_name 管理员名称
     * @return array
     * @since 1.0 2015-3-6 by sutroon
     */
    public function save_admin($admin_name) {
        $validator = array(
            array('user_name', 'require', '用户名无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('user_name', 'require', '用户名已被注册!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('password', 'require', '密码无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('user_state', 'number', '状态有误!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        $is_edit = I('id') ? true : false;
        $user_name=I('user_name');
        if (!$this->validate($validator)->create()) {
            D('Log')->log_user_operate(false, $user_name, array(
                'admin_name' => $admin_name,
                'desc' => sprintf('%s管理员账户失败 user=%s %s', ($is_edit ? '编辑' : '新增'), $user_name, implode('; ', $this->getError())),
                'action' => ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD),
                'level' => LogModel::LEVEL_INFO,
            ));
            return $this->returnMsg(false, $this->getError());
        }
        $data = $this->data;
        if ($is_edit) {
            $this->data['update_time'] = date('Y-m-d H:i:s'); // 更新编辑时间
            $result = $this->save();
        } else {
            $this->data['regist_ip'] = get_client_ip(); // 注册IP
            $result = $this->add();
            if (false !== $result) {
                // D('DbTable')->create_table('CDR', sofn_get_sharding_field('DB_CDR_HISTORY', '%s.') . 'cdr_' . $data['site_id']);
            }
        }
        D('Log')->log_user_operate($result, $user_name, array(
            'admin_name' => $admin_name,
            'desc' => sprintf('%s管理员账户%s user=%s', ($is_edit ? '编辑' : '新增'), '{%}', $user_name),
            'action' => ($is_edit ? LogModel::ACTION_EDIT : LogModel::ACTION_ADD),
            'level' => LogModel::LEVEL_INFO,
        ));
        return $this->returnMsg($result);
    }

    /**
     * 删除管理员
     * @param string $id 主键编号,多个之间以逗号隔开
     * @param int $admin_id 操作员编号
     * @return array
     * @since 1.0 <2015-6-10> SoChishun Added.
     */
    public function admin_delete($id, $admin_id) {
        if (!$admin_id) {
            return $this->returnMsg(false, '管理员无效');
        }
        if (!$id) {
            return $this->returnMsg(false, '编号无效');
        }
        $result = $this->query("select func_delete_admin('$id')");
        $code = current($result[0]);
        $status = $code == 1;
        $msg = $code > 1 ? sofn_get_procedure_result_text($code, array(4301 => '分机未清理', 4302 => '队列未清理', 4303 => '中继未清理', 4304 => '语音未清理', 4305 => '语音菜单未清理', 4306 => '策略未清理', 4307 => '自动登录未清理', 4308 => '来话导航未清理')) : '';
        D('Log')->log_user_operate($status, "删除管理员账户($id){%} $msg,操作员:$admin_id", $admin_id, LogModel::ACTION_DELETE);
        $this->clear_table_caching(array('tuser'));
        return $this->returnMsg($status, $msg);
    }

    /**
     * 返回列表
     * @return array
     * @xince 1.0 <2015-6-9> SoChishun Added.
     */
    public function get_admin_list($where) {
        $orderby = I('sort', $this->_scope['item_list']['order']) . ' ' . I('order');
        $page = I('page', 1) . ',' . I('rows', C('USER.PAGE_SIZE'));
        $total = $this->cache(true)->where($where)->count('id');
        $list = $this->cache(true)->scope('item_list')->where($where)->order($orderby)->page($page)->select();
        $roles = $this->table('tuser_role')->cache(true)->getField('id,role_name');
        foreach ($list as $row) {
            if ($roles) {
                $row['role_text'] = $roles[$row['role_id']];
            }
            $row['user_state_text'] = sofn_get_state_text('user-state', $row['user_state']);
            $row['online_state_text'] = sofn_get_state_text('online-state', $row['user_state']);
            $out[] = $row;
        }
        return array('total' => $total, 'rows' => $out);
    }

}
